package cn.txun05.csmall.passport.security;

import cn.txun05.csmall.passport.mapper.AdminMapper;
import cn.txun05.csmall.passport.pojo.vo.AdminLogInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 实现UserDetailsService接口，重写loadUserByUsername
 * 使用@Service将此类变为组件类，该类的对象被Spring容器接口
 * 当用户登录时，填写用户名和密码，Spring Security框架
 * 自动调用loadUserByUsername方法，该方法封装了用户详细信息
 * 包括密码、权限、启用状态等，以UserDetail对象返回给Security
 * Security自动比对用户密码是否正确，是否启用，等等。以此判断
 * 该用户是否可以登录
 */
@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("Spring Security框架自动调用了UserDetailsServiceImpl.loadUserByUsername()方法，用户名:{}",username);
        AdminLogInfoVO logInfoVO = adminMapper.getLoginInfoByUsername(username);
        log.debug("根据用户名【{}】从数据库中查询匹配的管理员信息，结果：{}",username,logInfoVO);
        //如果为null，说明查无此人
        if(logInfoVO==null){
            log.debug("此用户名没匹配的用户数据，将返回null");
            return null;
        }
        log.debug("用户名匹配成功，准备返回此用户名匹配的UserDetails类型的对象");
        //创建权限集合，封装权限
        List<String> permissions = logInfoVO.getPermissions();
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission: permissions){
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        //创建UserDetails对象，封装用户详细信息
        AdminDetails userDetails =
                new AdminDetails(logInfoVO.getId(),
                        logInfoVO.getUsername(),
                        logInfoVO.getPassword(),
                        logInfoVO.getEnable()==1,
                        authorities);
        log.debug("即将向Spring Security返回UserDetails类型的对象:{}",userDetails);

        return userDetails;
    }
}
